<?php
class CommentsController extends AppController {
    public function beforeFilter() {
        $this->Auth->allow('add');
        
        if($this->Session->check('mixedTimes')) {
            if(time() - (int)$this->Session->read('mixedTimes') < 1) {
            $this->Session->write('mixedTimes', time());
            $this->redirect(array('controller' => 'error', 'action' => 'fasterror'));
            }
        }
    }
    
    public function isAuthorized($user) {
        $this->loadModel('User');
        $this->User->id = $user['id'];
        $this->User->unbindModel(array('hasMany' => array('Test')));
        $role = $this->User->read('role');
        if($role['User']['role'] == 'none') {
            if(in_array($this->action, array('add'))) {
                return true;
            }
        }
        if($role['User']['role'] == 'admin') {
            if(in_array($this->action, array('add', 'view'))) {
                return true;
            }
        }
    }
    
    public function index() {
        $this->redirect(array('controller' => 'comments', 'action' => 'add'));
    }
    
    public function add() {
        $this->set('title_for_layout', 'Liên hệ - góp ý :: ChomoTech');
        if($this->Auth->loggedIn()) {
            $this->loadModel('User');
            $this->User->unbindModel(array('hasMany' => array('Test')));
            $this->User->id = $this->Auth->user('id');
            $this->set('user_mail', $this->User->read('email'));
        }
        if($this->request->is('post')) {
            $this->Session->write('mixedTimes', time());
            if($this->Comment->save($this->request->data['Comment'], true, array('content', 'email', 'captcha'))){
                $this->redirect(array('controller' => 'index'));
            }
        }
    }
    public function view($id) {
        
    }
}
?>